package com.deltabot.master.webserver;

import com.deltabot.master.heartbeatserver.*;
import com.deltabot.master.util.sharedUtils;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;


public class htmlHandler {

    public static String getIndexPage(){
        long start = System.nanoTime();  //To measure the page generation time

        String Response = "";

        try {
            Response = readFile(System.getProperty("user.dir") + "/index.html", Charset.defaultCharset());
        } catch (IOException e) {
            System.out.println(e);
        }
        try{
            if(!(Response == "")) Response = Response.replace("<!--DELTABOT:INSERT_TABLE-->", generateServerTable());

        } catch (IllegalArgumentException e){
           // Could fail due to some currently unknown bug, it'll write out an error if it does
            Response = "<h1>A fatal error has occured, please notify the staff about this error</h1>";
        }

        Long end = System.nanoTime();
        Long nsT = (end - start) / 1000;

        if(!(Response == "") && Response.contains("<!--DELTABOT:INSERT_GENERATEDTIME_STRING-->")){
            Response = Response.replace("<!--DELTABOT:INSERT_GENERATEDTIME_STRING-->","Page generated in " + generateTime(nsT) +" seconds");
        }

        if(!(Response == "") && Response.contains("<!--DELTABOT:INSERT_SERVERTOTAL-->")){
            Response = Response.replace("<!--DELTABOT:INSERT_SERVERTOTAL-->",cache.getCachedServers().length + " servers in cache");
        }

        if(!(Response == "") && Response.contains("<!--DELTABOT:INSERT_UPTIME-->")){
            Response = Response.replace("<!--DELTABOT:INSERT_UPTIME-->", sharedUtils.upTime + " seconds");
        }

        return Response;

    }

    private static String generateTime(Long nsT){
        String result = "0.00000123"; //Just some dummy time, incase our calculation fails
        if (nsT >= 1000000){
            result = String.valueOf(nsT).charAt(0) +  "." + String.valueOf(nsT).replace(String.valueOf(String.valueOf(nsT).charAt(0)),"");
        }
        else if (nsT >= 100000){
            result = "0." + nsT;
        }
        else if (nsT >= 10000){
            result = "0.0" + nsT;
        }
        else if (nsT >= 1000){
            result = "0.00" + nsT;
        } else {
            result = "0.000" + nsT;
        }

        return result;
    }

    private static String generateServerTable(){

        List<String> resultList = new ArrayList<String>();

        if(cache.getCachedServers().length > 0){

            resultList.add("<th style=\"cursor: pointer;\">Game</th>\n");
            resultList.add("<th style=\"cursor: pointer;\">Hostname</th>\n");
            resultList.add("<th style=\"cursor: pointer;\">IP</th>\n");
            resultList.add("<th style=\"cursor: pointer;\">Map</th>\n");
            resultList.add("<th style=\"cursor: pointer;\">Gametype</th>\n");
            resultList.add("<th style=\"cursor: pointer; padding-left: 8px;\">Players</th>\n");

        } else {
            resultList.add("<h1><center>No servers in our cache yet :(</center></h1>");
        }

        for(com.deltabot.master.heartbeatserver.server GameServer : cache.getCachedServers())       {

            resultList.add("<tr>\n");

           if(GameServer.Game.equals("MW")){
               resultList.add("<td id=\"cod4icon\" sorttable_customkey=\"1\"></td>\n");
           } else if (GameServer.Game.equals("WAW")){
               resultList.add("<td id=\"cod5icon\" sorttable_customkey=\"2\"></td>\n");
           } else if (GameServer.Game.equals("MW2")){
               resultList.add("<td id=\"cod6icon\" sorttable_customkey=\"3\"></td>\n");
           } else if (GameServer.Game.equals("BO")){
               resultList.add("<td id=\"cod7icon\" sorttable_customkey=\"4\"></td>\n");
           } else if (GameServer.Game.equals("MW3")){
               resultList.add("<td id=\"cod8icon\" sorttable_customkey=\"5\"></td>\n");
           } else if (GameServer.Game.equals("BO2")){
               resultList.add("<td id=\"cod9icon\" sorttable_customkey=\"6\"></td>\n");
           }


            //Make the hostname smaller if its > 100 chars to prevent our table from being streched out over the entire place
            String hostname = "";
            if(GameServer.Hostname.length() > 80){
                hostname = GameServer.Hostname.substring(0,80);
            }

            resultList.add("<td class=\"tabletext\" name=\"hostname\">"+ GameServer.Hostname+ "</td>\n");
            resultList.add("<td>" + GameServer.IP + ":" + GameServer.Port + "</td>\n");
            resultList.add("<td><center>"+ GameServer.Map + "</center></td>\n");
            resultList.add("<td>"+ GameServer.GameType + "</td>\n");
            resultList.add("<td sorttable_customkey=\""+ (Integer.parseInt(GameServer.CurrentPlayers)) +"\"> "+ GameServer.CurrentPlayers + "/" + GameServer.MaxPlayers + "   </td>\n");
            resultList.add("</tr>\n");
        }

        StringBuffer result = new StringBuffer();

        for (String s : resultList){
            result.append(s);
        }

        resultList.clear(); //We want to clear out this memory

        return result.toString();
    }

    private static String readFile(String path, Charset encoding)
            throws IOException
    {
        byte[] encoded = Files.readAllBytes(Paths.get(path));
        return encoding.decode(ByteBuffer.wrap(encoded)).toString();
    }


}
